var express = require('express')
const fs = require('fs')
const path = require('path')
const sqlQuery = require('../../../module/sqlQuery')
const cryptoMD5 = require('../../../module/cryptoMD5')
const { uploadPath } = require('../../../module/canshu')

// 上传模块
const multer = require('multer')
const upload = multer({ dest: uploadPath })

var router = express.Router()

/* GET users listing. */
router.get('/', async function (req, res, next) {
  res.render('admin/users/userlist')
  // res.send('sdfsdfdf')
})

// 信息界面 编辑
router.get('/edit/:id', async function (req, res, next) {
  let sqlStr = `select * from user where id=?`

  // 获取角色列表
  const roleList = await getRoleList()
  const results = await sqlQuery(sqlStr, [req.params.id])
  // res.json(results)
  const options = { users: results[0], roleList, type: 'edit' }
  res.render('admin/users/selfInfo.ejs', options)
})

router.post('/edit', async function (req, res, next) {
  // console.log(req.body)
  const { username, password, email, mobile, roleid } = req.body
  await sqlQuery(
    `update user 
    set password=?,
    email=?,
    mobile=?,
    roleid=?
    where username=?`,
    [cryptoMD5(password), email, mobile, roleid, username]
  )
  res.json({
    code: 0,
    msg: '更新成功',
  })
})

// 信息界面 添加
router.get('/add', async function (req, res, next) {
  // 获取角色列表
  const roleList = await getRoleList()
  res.render('admin/users/selfInfo.ejs', {
    users: {
      avatarurl: '/public/images/default_avatar.jpg',
      roleid: 1,
    },
    roleList,
    type: 'add',
  })
})

router.post('/add', async function (req, res, next) {
  // console.log(req.body)
  const { username, password, email, mobile, roleid } = req.body

  const resultsSelect = await sqlQuery('select id from user where username=?', [
    username,
  ])
  if (resultsSelect.length > 0) {
    return res.json({
      code: 1,
      msg: '该用户名已存在',
    })
  }

  const sqlStr = `insert into user (id,username,password,email,mobile,roleid,status) values (?,?,?,?,?,?,?)`
  const results = await sqlQuery(sqlStr, [
    new Date().getTime(),
    username,
    cryptoMD5(password),
    email,
    mobile,
    roleid,
    1,
  ])
  // console.log(results)
  res.json({
    code: 0,
    msg: '添加成功',
  })
})

// 用户信息删除（update状态改位为 0 ）
router.post('/delete', async function (req, res, next) {
  // console.log(req.body)
  const { id } = req.body

  // 用户信息删除（update状态改位为 0 ）
  // const { username, password, email, mobile, roleid } = req.body
  const results = await sqlQuery('update user set status = 0 where id=?', [id])
  res.json({
    code: 0,
    msg: '删除成功',
    data: results,
  })
})

// 用户信息批量删除（update状态改位为 0 ）
router.post('/deleteall', async function (req, res, next) {
  // console.log(req.body)
  const { delArr } = req.body

  let userIdStr = ''

  delArr.forEach((element) => {
    userIdStr = userIdStr + element + ', '
  })

  userIdStr = userIdStr.substring(0, userIdStr.length - 2)

  const str = `update user set status = 0 where id in (${userIdStr})`

  const results = await sqlQuery(str)

  res.json({
    code: 0,
    msg: '删除成功',
    data: results,
  })
})

// 图片上传的路由
router.post('/imgupload', upload.single('imgFile'), async function (
  req,
  res,
  next
) {
  // console.log(req.file)
  // console.log(req.query);
  // 文件重命名（加上后缀名）
  const oldPath = path.join(req.file.destination, req.file.filename)
  const newPath = path.join(
    req.file.destination,
    req.file.filename + '.' + req.file.originalname.split('.')[1]
  )

  fs.renameSync(oldPath, newPath)

  const { name, ext } = path.parse(newPath)
  // 转换成 /public/upload 路径保存到数据库
  const resPath = path.join('/public/upload', name + ext)
  // 数据库用户头像地址信息更新
  await sqlQuery('update user set avatarurl=? where id=?', [
    resPath,
    req.query.id,
  ])

  res.json({
    state: 'ok',
    resPath,
  })
})

// 获取角色列表
async function getRoleList() {
  const sqlStr = `select * from rolelist`
  const results = await sqlQuery(sqlStr)
  // res.json(results)
  return results
}

router.get('/data', async function (req, res, next) {
  // keywords 搜索关键词 为空的时候 查询全部
  let { page, limit, keywords = '', keywords2 = '' } = req.query
  console.log(req.query)

  page = parseInt(page ? page : 1)
  limit = parseInt(limit)
  const results = await sqlQuery(
    'SELECT user.id,username,email,mobile,avatarurl,rolename FROM `user` LEFT JOIN rolelist ON user.roleid=rolelist.id where status=1 and username like ? and rolelist.rolename like ? limit ?,?',
    ['%' + keywords + '%', '%' + keywords2 + '%', (page - 1) * 5, limit]
  )

  // 符合条件的总条数
  const [
    { count_num },
  ] = await sqlQuery(
    'SELECT count(user.id) as count_num from user LEFT JOIN rolelist ON user.roleid=rolelist.id where status=1 and username like ? and rolename like ? ',
    ['%' + keywords + '%', '%' + keywords2 + '%']
  )
  const resData = {
    code: 0,
    msg: '完成',
    count: count_num,
    data: Array.from(results),
  }
  res.json(resData)
  // res.render('admin/users/userlist',{userlist:results});
})

module.exports = router
